<?php 

/**
* 模型类
*/
class Model 
{
	// 存储链接对象的
	public static $model;

	public  $tablename;
	// 构造函数，实例化自动执行

	public $opt = array(
		'where'=>'',
		'limit'=>'',
		'select'=>''
		);

	public function __construct($tablename='')
	{
		$this->tablename= !empty($tablename) ? $tablename : '';
		// 判断链接对象是否已经存在
		if($this::$model){
			return;
		}

		// 通过配置获取链接数据库需要的值
		$host = C('DB_HOST');
		$dbname = C('DB_DATABASES');
		$username =C('DB_USERNAME');
		$password = C('DB_PASSWORD');
		$code = C('DB_UTF');

		// 尝试链接数据库
		try{
			$pdo = new Pdo("mysql:host=$host;dbname=$dbname",$username,$password);
		}catch(PDOException $e) {
			die($e->getMessage()); 
		}
		// 设置编码
		$pdo->query("SET NAMES $code");
		//存储链接对象的
		$this::$model=$pdo;

	}

	public function queryAll($sql)
	{
		// 执行查询的SQL
		$result = $this::$model->query($sql);
		// var_dump($result);

		//返回执行关联数组结果
		return $result->fetchAll(PDO::FETCH_ASSOC);
	}

	public function select($data)
	{
		$this->opt['select']=$data;
		return $this;
	}

	public function limit($data)
	{
		$this->opt['limit']=$data;
		return $this;
	}


	public function where($data)
	{
		$this->opt['where']=$data;
		return $this;
	}

	public function query(){

		$sql = "select ".$this->opt['select']." from ".$this->tablename." where ".$this->opt['where']." limit ".$this->opt['limit'];

// var_dump($sql);
		return $this->queryAll($sql);

	}


}









 ?>